/**
 * 图片上传下载
 * 使用示例
 * <div class="field" data-jss-upload data-path="bookAttachment" data-file-model="bookRecommended.fileModel"
 data-file-bs-id="bookRecommended.id"  data-is-mul="true"></div>
 data-img-upload 指令名称
 data-path 文件保存路径
 data-file-model 文件回传保存对象，用于传递到后台保存
 data-file-bs-id 保存关联的业务id 一般是业务表主键id或者文件保存的id
 data-is-mul 表式是否多文件上传（同时选择多个文件）
 data-file-max-length 文件个数
 * author ningbo2 2014-05-12
 */

define(["app",
    "comm/js/directives/FileInput",
    "comm/js/services/FileResource",
    "comm/js/services/MessageBox"], function (app) {

    var deps = ["$timeout", "$http", "FileResource", "MessageBox"];

    /**
     * 指令主体
     */
    function directive ($timeout, $http, FileResource, MessageBox) {

        return {
            restrict: "A",
            scope: {
                fileModel: "=fileModel",
                fileBsId: "=fileBsId",
                path: "@path",
                isAppend: "@isAppend",
                isMul: "@isMul",
                fileMaxLength: "@fileMaxLength"
            },
            templateUrl: "views/common/upload/imgUpload.html",
            replace: true,
            link: function (scope, element, attrs) {

                /**
                 * 初始化数据 ，防止undefined
                 */
                function loadData (scope, data) {
                    scope.isAppend = scope.isAppend || "true";
                    scope.fileModel = scope.fileModel || {};
                    scope.fileModel.picList = data || scope.fileModel.picList || [];
                    scope.fileModel.path = scope.fileModel.path || scope.path;
                    scope.fileModel.files = scope.fileModel.files || [];
                    scope.fileModel.tempfiles = scope.fileModel.tempfiles || [];
                    scope.fileModel.deletefiles = scope.fileModel.deletefiles || [];
                    scope.fileModel.deleteFiles = scope.fileModel.deleteFiles || [];
                }

                scope.isMul = scope.isMul || "true";
                scope.path = scope.path || "tempfile";
                scope.fileMaxLength = scope.fileMaxLength || 1;
                scope.state = {};

                /**
                 * 监控业务id变化 初始化数据
                 */
                scope.$watch("fileBsId", function () {
                    if (scope.fileBsId && scope.fileBsId != "") {
                        // //如果业务id存在 根据是否多文件上传 调用不同的接口初始化数据
                        // if(scope.isMul=="true"){
                        // 	// //附件接口
                        // 	// FileResource.getFiles(scope.path + scope.fileBsId).success(
                        // 	// 		function(data) {
                        // 	// 			debugger;
                        // 	// 			loadData(scope, data);
                        // 	// 		});
                        // } else {
                        // //图片接口
                        // FileResource.getPic(scope.fileBsId).success(
                        // 		function(data) {
                        // 			debugger;
                        // 			loadData(scope, data);
                        // 		});
                        loadData(scope, scope.fileBsId.split(','));
                        // }
                    } else {
                        loadData(scope, "");
                    }

                });

                //监听文件变化，自动上传
                scope.$watch("state.files", function () {
                    if (scope.state.files && scope.state.files.length > 0) {
                        var error = "";
                        angular.forEach(scope.state.files, function (file) {
                            //console.log(file.type);
                            if (file.type.indexOf("image/") < 0) {
                                error = "文件格式不正确！只能上传（.jpg、.png、.gif、.tiff、.bmp、.dwg）格式结尾的文件";
                                MessageBox.notify(error);
                                scope.state.files.splice(0, 1);
                                return false;
                            }
                            if (file.size >= 52428800) {
                                error = "文件过大！只能上传小于50M的文件";
                                MessageBox.notify(error);
                                scope.state.files.splice(0, 1);
                                return false;
                            }
                        });
                        scope.upload();
                    }
                });

                /**
                 * 上传文件
                 */
                scope.upload = function () {
                    showLoading(' ');
                    scope.uploading = true;
                    var fileNum = scope.state.files.length;
                    if (fileNum == 0) {
                        return;
                    }
                    var success = 0;
                    var fd = new FormData();
                    angular.forEach(scope.state.files, function (file) {
                        fd.append("file", file);
                        if (file.type == "") {
                            error = "文件格式不正确！只能上传（.jpg、.png、.gif、.tiff、.bmp、.dwg）格式结尾的文件";
                            hideLoading();
                            MessageBox.notify("错误发生：" + error);
                            scope.state.files.splice(0, 1);
                            return false;
                        }
                        if (file.size >= 52428800) {
                            error = "文件过大！只能上传小于50M的文件";
                            hideLoading();
                            MessageBox.notify("错误发生：" + error);
                            scope.state.files.splice(0, 1);
                            return false;
                        }
                    });
                    FileResource.upload(scope.path, scope.isAppend, fd).success(function (data) {
                        scope.uploading = false;
                        // MessageBox.notify("上传成功");
                        // if(scope.isMul=="false"){
                        if (scope.fileModel.deletefiles.length == 0) {
                            scope.fileModel.deletefiles = scope.fileModel.files;
                        }
                        scope.fileModel.tempfiles = [];
                        scope.fileModel.files = [];
                        // }
                        //循环上传文件 这里返回的对象为{fileId，fileName } 需要转换一下
                        if (data instanceof Array) {
                            for (var i = 0; i < data.length; i++) {
                                var filedata = {};
                                filedata.id = data[i].fileId;
                                filedata.fileName = data[i].fileName;
                                scope.fileModel.tempfiles.push(filedata);
                            }
                        } else {
                            var filedata = {};
                            filedata.id = data.fileId;
                            filedata.fileName = data.fileName;
                            scope.fileModel.tempfiles.push(filedata);
                        }

                        scope.state.files.splice(0, scope.state.files.length);

                        FileResource.savePics(scope.fileModel).success(function (rto) {
                            if (rto.code == 1001) {
                                for (var i = 0; i < rto.data.length; i++) {
                                    scope.fileModel.picList.push(rto.data[i]);
                                }
                                scope.fileBsId = scope.fileModel.picList.toString();
                            } else {
                                MessageBox.notify("错误发生：" + rto.msg);
                                scope.submiting = false;
                            }
                            hideLoading();

                        }).error(function () {
                            MessageBox.notify("系统错误，请联系管理员！");
                            scope.submiting = false;
                            hideLoading();

                        });

                    });

                };
                scope.delPic = function (pic) {
                    scope.fileModel.picList.removeItem(pic);
                    scope.fileBsId = scope.fileModel.picList.toString();
                    scope.fileModel.deleteFiles.push(pic);
                };

                /**
                 * 移除未上传的文件
                 */
                scope.removeFile = function (file, $event) {
                    for (var i = 0; i < scope.state.files.length; i++) {
                        var item = scope.state.files[i];
                        if (file.$$hashKey == item.$$hashKey) {
                            scope.state.files.splice(i, 1);
//							var $filediv = $($event.target).parents("[data-jss-Upload]"); 
//							var $fileinput = $filediv.find("#fileinput");
//							var files = $fileinput.files;
//							$fileinput.files=scope.state.files;
                            break;
                        }
                    }
                };

                /**
                 * 移除已上传的文件
                 */
                scope.removeUploadedFile = function (id) {
                    for (var i = 0; i < scope.fileModel.tempfiles.length; i++) {
                        if (id == scope.fileModel.tempfiles[i].id) {
                            scope.fileModel.tempfiles.splice(i, 1);
                            break;
                        }
                    }
                };

                /**
                 * 移除已保存的文件
                 */
                scope.removeSaveFile = function (id) {
                    for (var i = 0; i < scope.fileModel.files.length; i++) {
                        if (id == scope.fileModel.files[i].id) {
                            scope.fileModel.deletefiles.push(scope.fileModel.files[i]);
                            scope.fileModel.files.splice(i, 1);
                            break;
                        }
                    }
                };

            }
        };
    }

    directive.$inject = deps;
    app.lazy.directive("imgUpload", directive);
});